package dao;

import application.exceptions.ItemNotFoundException;
import mappings.Features;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import utils.HibernateUtil;

import java.util.List;

@SuppressWarnings("JpaQlInspection")
public class FeaturesDao
{
    private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public List<Features> getAllFeatures()
    {
        Session session = sessionFactory.openSession();

        List<Features> features = session.createCriteria(Features.class)
                .list();

        session.close();

        return features;
    }

    public Features addFeature(String name)
    {
        Features feature = new Features();
        feature.setName(name);

        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        session.save(feature);

        tx.commit();
        session.close();

        return feature;
    }

    public Features editFeature(Integer id, Features feature) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        Features featureToEdit = (Features) session.get(Features.class, id);

        if(featureToEdit == null)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        featureToEdit.setName(feature.getName());
        session.update(featureToEdit);
        tx.commit();
        session.close();

        return featureToEdit;
    }

    public void deleteFeature(Integer id) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        int affectedRows = session.createQuery("delete Features where id = :id")
                .setParameter("id", id)
                .executeUpdate();

        if(affectedRows == 0)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        tx.commit();
        session.close();
    }
}
